#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
#include <QMessageBox>
#include<QUndoStack>
#include<QTextEdit>

class MyCommand : public QUndoCommand
{
public:
    MyCommand(QTextEdit *editor, const QString &text, QUndoCommand *parent = nullptr)
        : QUndoCommand(parent), m_editor(editor), m_oldText(text), m_text(editor->toPlainText()) {}

    void undo() override
    {
        m_editor->setPlainText(m_oldText);
    }

    void redo() override
    {
        m_editor->setPlainText(m_text);
    }

private:
    QTextEdit *m_editor;
    QString m_text;
    QString m_oldText;
};

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    QObject::connect(ui->actionundo, &QAction::triggered, &stack, &QUndoStack::undo);
    QObject::connect(ui->actionredo,  &QAction::triggered, &stack, &QUndoStack::redo);

    ui->actionredo->setEnabled(false);
    ui->actionundo->setEnabled(false);
   //QObject::connect(ui->textEdit, &QTextEdit::textChanged,this, &MainWindow::on_actionsavestate_triggered);


   //void canUndoChanged(bool canUndo);
   //void canRedoChanged(bool canRedo);
    QObject::connect(&stack, &QUndoStack::canRedoChanged, [&](bool f) {
        ui->actionredo->setEnabled(f);
    });
    QObject::connect(&stack, &QUndoStack::canUndoChanged, [&](bool f) {
        ui->actionundo->setEnabled(f);
    });
}

MainWindow::~MainWindow()
{
    delete ui;
}



void MainWindow::on_actionsavestate_triggered()
{
    ischange=true;
    qDebug()<<"编辑前： "<< lastText<<endl;
    stack.push(new MyCommand(ui->textEdit, lastText));
    lastText = ui->textEdit->toPlainText();
}

